/*
 * Copyright (c) 2002-2012 Alibaba Group Holding Limited.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zxg.zbc.web.home.module.screen;

import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.requestcontext.parser.ParameterParser;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.zxg.weixin.api.service.WeixinPayService;
import com.zxg.zbc.biz.exception.ManagerException;
import com.zxg.zbc.biz.manager.PayServiceManager;
import com.zxg.zbc.web.common.module.BaseWeixinPayResult;

/**
 *
 * @author Hangding
 */
public class WeixinNotify extends BaseWeixinPayResult {

  @Autowired
  WeixinPayService  weixinPayService;
  @Autowired
  PayServiceManager payServiceManager;

  @Override
  protected String doExecute(Context context, ParameterParser params, Navigator nav, Document postReadData) {
    if (postReadData.getRootElement().element("result_code") != null
        && postReadData.getRootElement().element("result_code").getTextTrim().equalsIgnoreCase("success")) {
      String outid = postReadData.getRootElement().element("out_trade_no").getTextTrim();
      String trade_no = postReadData.getRootElement().element("transaction_id").getTextTrim();
      String openid = postReadData.getRootElement().element("openid").getTextTrim();
      String totalFee = postReadData.getRootElement().element("cash_fee").getTextTrim();
      if (outid != null) {
        if (weixinPayService.verifyTradeSuccess(outid)) {
          log.warn("weixinpay process");
          try {
            payServiceManager.generatePayResult(Boolean.TRUE, outid, trade_no, "TRADE_SUCCESS", openid, totalFee);

            String rtn = "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";
            return rtn;

          } catch (ManagerException e) {
            log.error("erroree,", e);
          }
        }
      }

    }
    return null;
  }

}
